--[[
FilePath: \Lua\View\UIActivityCenter\UIActivityListExchange.lua
周期兑换- 资源兑换
--]]

require 'View/UIBase/UIBase'

UIActivityListExchange = UIBase.New(PanelResNames.UIActivityListExchange)
local _M = UIActivityListExchange

_M.hasInit = false
_M.activeId = nil
_M.ContentItems = {}
_M.playEffect = false
_M.activityTabConfig = nil
_M.RoleLihui = nil
_M.showTimeMode = nil   --1,普通活动 2，春节活动

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Backbtn"), self.OnClose)
        self.btnHelp = self:GetChild("help")
        self.banner = self:GetChild("bannerBg")
        self.TopPic = self:GetChild("TopPic")

        self.activityTitleIcon = self:GetChild("activityTitleIcon")
        self.bgChunjieTop = self:GetChild("BG_chunjie_top")
        self.bgChunjieMid = self:GetChild("BG_chunjie_mid")
        self.bgChunjieDown = self:GetChild("BG_chunjie_down")
        self.bgChunjieHero = self:GetChild("BG_chunjie_Hero")
        self.txtChunjieTips = self:GetChild("ActivityTips")
        self.heroIcon = self:GetChild("HeroIcon");

        --self.bannerChar = self:GetChild("bannerChar")
        self.title = self:GetChild("n16"):GetChild("title");
        self.itemList = self:GetChild("list")
        self.CashLb = self:GetChild("CashLb");
        self.CoinLb3 = self:GetChild("CoinLb3");
        self.CoinLb = self:GetChild("CoinLb");
        self.speakTitle = self:GetChild("speaktitle");
        self.lihui = self:GetChild("lihui");
        self.lihui2 = self:GetChild("lihui2");
        self.tipTime = self:GetChild("tipTime");
        self.DrawBtn = self:GetChild("DrawBtn");
        self.ctr_check = self:GetController("Buttoncheck")
        self.btn_check = self:GetChild("Buttoncheck")

        self.ctr_check.selectedIndex = ActiveManager.GetExchangeRedDotState() and 1 or 0

        self.btn_check.onClick:Add(self.OnCheckStateChange)
        if self.activeId ~= nil then
            _M.activityTabConfig = G.dataTable["t_activitylist"][tostring(self.activeId)];
            self.activeConfigModel = G.dataTable[tostring(_M.activityTabConfig.f_ModelName)][tostring(self.activeId)];
        end
        self.DrawBtn.visible = self.activeConfigModel.f_Functionswitchid ~= 0;
        self.itemList.itemRenderer = self.RefreshItem;

        self:addEvent()
        self:InitView()
        _M.hasInit = true
    end
end

function _M:addEvent()
    self.btnHelp.onClick:Add(self.HelpTip)
    self:RegisterOnClick(self.DrawBtn,  self.OnClickDraw)
    self:RegisterEvent(Config.EventType.Fresh_Active,self.RefreshActive);
end

function _M:removeEvent()
    self.btnHelp.onClick:Remove(self.HelpTip)
end

function _M:OnClose()
    self:OnBack();
    logicMgr.HeroManager.setGetNewHeroShow();
end

function _M.HelpTip()
    if _M.activeConfigModel ~= nil and _M.activeConfigModel.f_ExplainTitle ~= nil and _M.activeConfigModel.f_ExplainText ~= nil then
        logicMgr.UIShowManager.ShowCommonTips(tostring(_M.activeConfigModel.f_ExplainTitle), tostring(_M.activeConfigModel.f_ExplainText));
    end
end

function _M:OnClickDraw()
    logicMgr.FuncOpenManager.jump(self.activeConfigModel.f_Functionswitchid, true);
    self:OnClose()
end

-- 显示
function _M:OnEnable()
    self.playEffect = true;
    self:Refresh();
    logicMgr.HeroManager.setGetNewHeroShow(true);
    if self.activeId ~= nil then
        logicMgr.ActiveManager.updateActiveOpenStatus(self.activeId);
    end
end

function _M:InitView()
    if self.activeConfigModel ~= nil then
        if self.activeConfigModel.f_BgPic ~= nil and self.activeConfigModel.f_BgPic ~= "" then
            self.banner.url = self.activeConfigModel.f_BgPic;
        end
        if self.activeConfigModel.f_activityTitleIcon ~= nil and self.activeConfigModel.f_activityTitleIcon ~= "" then
            self.activityTitleIcon.url = self.activeConfigModel.f_activityTitleIcon;
        end
        if self.activeConfigModel.f_chunjietop ~= nil and self.activeConfigModel.f_chunjietop ~= "" then
            self.bgChunjieTop.url = self.activeConfigModel.f_chunjietop;
        end
        if self.activeConfigModel.f_chunjiemid ~= nil and self.activeConfigModel.f_chunjiemid ~= "" then
            self.bgChunjieMid.url = self.activeConfigModel.f_chunjiemid;
        end
        if self.activeConfigModel.f_chunjiedown ~= nil and self.activeConfigModel.f_chunjiedown ~= "" then
            self.bgChunjieDown.url = self.activeConfigModel.f_chunjiedown;
        end
        if self.activeConfigModel.f_activityHerobg ~= nil and self.activeConfigModel.f_activityHerobg ~= "" then
            self.bgChunjieHero.url = self.activeConfigModel.f_activityHerobg;
        end
        if self.activeConfigModel.f_chunjiemidTips ~= nil and self.activeConfigModel.f_chunjiemidTips ~= "" then
            self.txtChunjieTips.text = getLanguage(self.activeConfigModel.f_chunjiemidTips);
        end
        if self.activeConfigModel.f_HeroIcon and self.activeConfigModel.f_HeroIcon ~= "" then
            self.heroIcon.url = tostring(self.activeConfigModel.f_HeroIcon)
        end
        if self.activeConfigModel.f_ActivityTipsTime ~= nil and self.activeConfigModel.f_ActivityTipsTime ~= "" then
            self.showTimeMode = 1
            self.tipTime.visible = true
        else
            self.showTimeMode = 2
            self.tipTime.visible = false
        end
        self.title.text = getLanguage(self.activeConfigModel.f_ActivityName);
        self.speakTitle.text = getLanguage(self.activeConfigModel.f_SpeakTitle);
        self.costItemId = decodeJsonStrToTabel(self.activeConfigModel.f_CostItemId);

        self.CashLb.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"][tostring(self.costItemId[1])].f_Icon;
        if #self.costItemId == 1 then
            self.CoinLb3.visible = false;
        elseif #self.costItemId == 2 then
            self.CoinLb3.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"][tostring(self.costItemId[2])].f_Icon;
        end
        self.CoinLb.icon = EnumConst.AtlasPath.ItemAtlas .. G.dataTable["t_item"]["1"].f_Icon;
        self.TopPic.url = self.activeConfigModel.f_TopPic
        if self.activeConfigModel.f_HeroSpine ~= nil then
            if self.activeConfigModel.f_HeroSpine[2] and self.activeConfigModel.f_HeroSpine[2] == 1 then
                local imageName = logicMgr.HeroManager.GetHeroDrawingPath(self.activeConfigModel.f_HeroSpine[1])
                if self.drawWrapper == nil then
                    self.drawWrapper = GoWrapper.New()
                end

                resMgr:LoadModelPrefab(imageName, function(go)
                    if(self.RoleLihui~=nil)then
                        destroyImmediate(self.RoleLihui);
                        self.RoleLihui = nil
                    end
                    self.RoleLihui = newObject(go);
                    self.RoleLihui.name = imageName;
                    Util.AddAction(self.RoleLihui,"idle1",true,0.5);
                    self.RoleLihui:AddComponent(TCanvas);
                    self.drawWrapper:SetWrapTarget(self.RoleLihui,false);
                    local scale = self.activeConfigModel.f_HeroSpine[4];
                    Util.Lua_SetLocalPositionXYZ(self.RoleLihui.transform,0,0,0)
                    Util.Lua_SetLocalScaleXYZ(self.RoleLihui.transform,scale,scale,scale)
                    self.lihui:SetNativeObject(self.drawWrapper);
                end)
            elseif self.activeConfigModel.f_HeroSpine[2] and self.activeConfigModel.f_HeroSpine[2] == 2 then
                local list = TablePool.Get()
                string_split(self.activeConfigModel.f_HeroSpine[1],"/",list)
                AddUIPackageDepend(PanelResNames.UIActivityListExchange,"FUI/"..list[1])
                TablePool.Release(list)
                self.lihui2.url ="ui://"..self.activeConfigModel.f_HeroSpine[1];
                Util.PlayAction(self.lihui2.wrapTarget, self.activeConfigModel.f_HeroSpine[3], true);
            end
        end
    end
end

function _M:RefreshActive()
    self.playEffect = false;
    self:Refresh();
end

_M.itemConfig = nil;
_M.serverDataTab = nil;
function _M:Refresh()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return;
        end
    end

    self.serverDataTab = nil;
    if self.itemConfig == nil then
        self.itemConfig = {};
        local config = G.dataTable[tostring(self.activeConfigModel.f_ItemTableName)];
        for k, v in pairs(config) do
            if tonumber(v.f_ActivityId) == tonumber(self.activeId) and logicMgr.CostManager.isOpenItem(v) then
                table.insert(self.itemConfig, v)
            end
        end
    end

    table.sort(self.itemConfig, function(a, b)
        local numA, stateA = self:GetServerData(a);
        local numB, stateB = self:GetServerData(b);
        if stateA > stateB then
            return true;
        end
        if stateA < stateB then
            return false;
        end
        return a.f_Id < b.f_Id;
    end)

    self.itemList.numItems = #self.itemConfig;
    if self.playEffect then
        self.itemList:ScrollToView(0);
        self.playEffect = false;
        HelperFunc.ListTranstionPlay(self.itemList)
    end

    local haveNum = logicMgr.ItemManager.getBagNumByTableID(1);
    self.CoinLb.title = haveNum;
    haveNum = logicMgr.ItemManager.getBagNumByTableID(tonumber(self.costItemId[1]));
    self.CashLb.title = getNumString(haveNum);
    if #self.costItemId == 2 then
        haveNum = logicMgr.ItemManager.getBagNumByTableID(tonumber(self.costItemId[2]));
        self.CoinLb3.title = getNumString(haveNum);
    end

    local time = HelperFunc.GetServerTime();
    self.endCountDown = self.serverData.endTime - time;
    self:updateActiveCountDown();
    self:TimeCall(self.updateActiveCountDown, 1000, -1);
end

function _M:updateActiveCountDown()
    if self.endCountDown == nil then
        return;
    end
    local showTimeTips = self.tipTime
    if self.showTimeMode == 2 then
        showTimeTips = self.txtChunjieTips
    end
    if self.endCountDown <= 0 then
        showTimeTips.text =  getLanguage("Sys_ActivityEnd");
        self:RemoveTimeCall(self.updateActiveCountDown)
    else
        showTimeTips.text = string.format(getLanguage("Sys_ActivityTimeLeft"), HelperFunc.GetSurpTimeStr(self.endCountDown));
    end
    self.endCountDown = self.endCountDown - 1;
end

function _M.RefreshItem(index, itemObj)
    _M:CreateItem(index, itemObj)
    local config = _M.itemConfig[index + 1];
    local num, state = _M:GetServerData(config);
    _M.ContentItems[index]:OnShow(config, num)
end

function _M:OnCheckStateChange()
    if _M.ctr_check.selectedIndex == 1 then
        _M.ctr_check.selectedIndex = 0
        logicMgr.ActiveManager.ExchangeSetRedDot(0)
    else
        _M.ctr_check.selectedIndex = 1
        logicMgr.ActiveManager.ExchangeSetRedDot(1)
    end
end

function _M:GetServerData(config)
    if self.serverData == nil then
        return 0, -1;
    end
    local num;
    if self.serverData.param ~= nil and self.serverData.param.buyCountMap ~= nil then
        num = self.serverData.param.buyCountMap[tostring(config.f_Id)];
    end
    if num == nil then
        num = 0;
    end
    if tonumber(num) >= tonumber(config.f_Limit) then
        return num, -1;
    else
        if tonumber(config.f_Sort) == 2 then
            return num, 2;
        end
        local costItem = decodeJsonStrToTabel(config.f_CostList)
        local engNum = 0;
        for i = 1, #costItem do
            local haveNum = logicMgr.ItemManager.getBagNumByTableID(tonumber(costItem[i][1]));
            local costNum = costItem[i][2];
            if tonumber(haveNum) >= tonumber(costNum) then
                engNum = engNum + 1;
            end
        end
        if engNum == #costItem and tonumber(config.f_Sort) ~= 0 then
            return num, 1;
        end
        return num, 0;
    end
end

function _M:CreateItem(index,itemObj)
    if self.ContentItems[index] then
        return
    end
    local item = self.UIActivityListExchangeItem.New()
    self.ContentItems[index] = item
    item:OnCreate(itemObj,self)
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    if(self.RoleLihui~=nil)then
        destroyImmediate(self.RoleLihui);
        self.RoleLihui = nil
    end

    if self.ContentItems then
        for key, value in pairs(self.ContentItems) do
            value:OnDestroy()
        end
        self.ContentItems = {}
    end
    self.itemConfig = nil;
end

-- item类
_M.UIActivityListExchangeItem = Class("UIActivityListExchangeItem",UIComponentInterface)
local _M_T = _M.UIActivityListExchangeItem
function _M_T:OnCreate(obj,parent)
    self.taskId = 0
    self.parent = parent
    self.fguiObj = obj
    self.isGet = false;
    
    self.rewardItem = obj:GetChild("item");
   -- self.costItemList = obj:GetChild("itemList");
    self.numLimit = obj:GetChild("numLimit");
    self.ntext = obj:GetChild("ntext");
    self.buy = obj:GetChild("buy");
    self.state = obj:GetController("state");
    self.limit = obj:GetController("limit");
    self.costList = obj:GetChild("n77");
    self.bg = obj:GetChild("bg");

    self.parent:RegisterOnClick(self.buy,self.ClickReward,self)
end
function _M_T:OnShow(itemConfig, bugNum)
    self.config = itemConfig;
    self.bugNum = tonumber(bugNum);
    self:Refresh()
end

function _M_T:Refresh()
    self.bg.url = self.parent.activeConfigModel.f_BtnPic
    local rewards = decodeJsonStrToTabel(self.config.f_SellingList)
    self.bagItemData = nil;
    local itemConfig = G.dataTable["t_item"];
    local rewardItem = itemConfig[tostring(rewards[1][1])];
    if rewardItem ~= nil then
        self.bagItemData = {};
        self.bagItemData.desc = getLanguage(rewardItem.f_Desc);
        self.bagItemData.icon = rewardItem.f_Icon;
        self.bagItemData.itemModelId = rewardItem.f_itemModelId;
        self.bagItemData.itemType = rewardItem.f_BagType;
        self.bagItemData.name = getLanguage(rewardItem.f_ItemName);
        self.bagItemData.num = rewards[1][2];
        self.bagItemData.quality = rewardItem.f_Quality;
        self.bagItemData.remainCount = tonumber(self.config.f_Limit) - self.bugNum;
    end
    logicMgr.CostManager.RefreshItem(self.rewardItem, rewards[1])
  --  logicMgr.CostManager.RefreshItemList(self.costItemList, decodeJsonStrToTabel(v.f_Reward), nil, {isShowBigNum = true});
    self.canBug = nil
    local costItem = decodeJsonStrToTabel(self.config.f_CostList)
    local engNum = 0;
    self.costList:RemoveChildrenToPool();
    self.costItemName = nil;
    local noEngMoneyType;
    local noEngMoneyPrice;
    local moneyType;
    local price;
    local excNum = -1;
    for i = 1, #costItem do
        local item = self.costList:AddItemFromPool();
        local icon = item:GetChild("icon");
        local costItemId = costItem[i][1];
        local itemConfig = itemConfig[tostring(costItemId)];
        icon.icon = EnumConst.AtlasPath.ItemAtlas .. itemConfig.f_Icon;
        local num = item:GetChild("num");
        local haveNum = tonumber(logicMgr.ItemManager.getBagNumByTableID(tonumber(costItemId)));
        local costNum = tonumber(costItem[i][2]);
        self.ntext.text = getLanguage("SellLimit");
        if haveNum >= costNum then
            local a, b = math.modf(haveNum / costNum);
            if excNum == - 1 or a < excNum then
                moneyType = costItemId;
                price = costNum;
                excNum = a;
            end
            engNum = engNum + 1;
            num.text = "[color=#A0C776]" .. haveNum .. "[/color]/" .. costNum;
        else
            if self.costItemName == nil then
                self.costItemName = itemConfig.f_ItemName;
            end
            num.text = "[color=#FF2A4D]"..haveNum.."[/color]/"..costNum;
            noEngMoneyType = costItemId;
            noEngMoneyPrice = costNum;
        end
    end
    if engNum == #costItem then
        self.canBug = true;
        if self.bagItemData ~= nil then
            self.bagItemData.monyType = moneyType;
            self.bagItemData.moneyIcon = tostring(moneyType);
            self.bagItemData.price = price;
        end
    else
        if self.bagItemData ~= nil then
            self.bagItemData.monyType = noEngMoneyType;
            self.bagItemData.moneyIcon = tostring(noEngMoneyType);
            self.bagItemData.price = noEngMoneyPrice;
        end
    end
    local limit = tonumber(self.config.f_Limit);
    if limit > 0 then
        local remain = limit - self.bugNum
        if remain < 0 then
            remain = 0
        end
        self.numLimit.text = remain .."/"..limit;
        self.limit.selectedIndex = 0
        if self.bugNum >= limit then
            self.state.selectedIndex = 1;
        else
            if self.canBug then
                self.state.selectedIndex = 0;
            else
                self.state.selectedIndex = 2;
            end
        end
    else
        self.limit.selectedIndex = 1
    end
end

function _M_T:OnHide()

end
function _M_T:OnDestroy()

end

function _M_T:ClickReward()
    if self.isGet then
        return;
    end

    if self.canBug == nil then
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),getLanguage(self.costItemName)))
        return;
    end
    if self.bagItemData ~= nil then
        showUI(PanelNames.UIBagItemInfo, self.bagItemData, 5, nil, nil, function(buyNum)
            self.isGet = true;
            ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, buyNum, tonumber(self.config.f_Id)});
            self:TimeCall(self.TimeEnd, 100);
        end);
    end
end

function _M_T:TimeEnd()
    self:RemoveTimeCall(self.TimeEnd)
    self.isGet = false;
end

return _M;